#####
# Replication for: "Can Political Speech Foster Tolerance of Immigrants?" by Schleiter, Tavits, and Ward.
# Figure 1
#####

library(here)
library(data.table)
library(ggplot2)
library(ggstance)
library(patchwork)

# source the custom functions (CI_machine() needed for this)
source("functions.R")

# load the pooled data if not already in workspace
if(!exists("pooled")){
  pooled <- fread(here("data", "pooled.csv"))
}


# Reshape, calculate CI, remove extra rows --------------------------------

pool_melt <- melt(pooled[wave != "Replication", .(mechanism_NM, mechanism_CS, mechanism_CH, Treatment)], id.vars = "Treatment")

to_plot <- pool_melt[ , CI_machine(value), by = .(Treatment, variable)]

to_plot <- to_plot[
  (Treatment == "Sleep") |
  (Treatment == "Common Humanity" & variable == "mechanism_CH") |
  (Treatment == "Norms" & variable == "mechanism_NM") |
  (Treatment == "Information" & variable == "mechanism_CS")
  ]

# Make pretty labels and y-axis positions ---------------------------------

facet_labels <- c(
  "Tolerance and acceptance of diversity are American values.",
  "Our economy benefits from the work of immigrants.",
  "All people, no matter where they are born, share a common humanity."
)

to_plot[ , facet_lab := fcase(
  variable == "mechanism_NM", facet_labels[1],
  variable == "mechanism_CS", facet_labels[2],
  variable == "mechanism_CH", facet_labels[3]
)]

# necessary to get ggplot facets in correct order
to_plot[ , facet_lab := factor(facet_lab, levels = facet_labels)]

treatment_labels <- c(
  "Norms",
  "Countering\nStereotypes",
  "Common\nHumanity",
  "Sleep\n(Control)"
)

to_plot[ , treat_lab := fcase(
  Treatment == "Norms", treatment_labels[1],
  Treatment == "Information", treatment_labels[2],
  Treatment == "Common Humanity", treatment_labels[3],
  Treatment == "Sleep", treatment_labels[4]
)]

# gets these in the correct order
to_plot[ , treat_lab := factor(treat_lab, levels = rev(treatment_labels))]


# plotting ----------------------------------------------------------

fig1 <- ggplot(to_plot, aes(x = main, y = treat_lab, fill = Treatment != "Sleep")) +
  geom_barh(stat = "identity") +
  geom_errorbarh(aes(xmin = lower, xmax = upper), color = "black", width = .25) +
  scale_fill_grey(name = "Treatment:", guide = "none", start = .4) +
  facet_wrap( ~ facet_lab , ncol = 1, scales = "free_y") +
  scale_x_continuous(breaks = c(0:3), limits = c(-0.1, 3), expand = expansion()) +
  ylab(NULL) +
  xlab("Mean Statement Rank") +
  theme(legend.position = "bottom",
        strip.text.x = element_text(size = 11, hjust = 0.5),
        strip.background = element_rect(fill= "white"),
        panel.grid.minor.x = element_blank()
  ) +
  coord_cartesian(xlim = c(1,3))

ggsave(here("main_text", "figure_1.pdf"), fig1, height = 8, width = 6)
